package icom.acm.manager.mircblog;

import icom.acm.bean.mircblog.T_MB_COMMENT;
import icom.acm.util.DBConnect;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class T_MB_CommentMgr {
	public int Insert(T_MB_COMMENT cmt){
		int flag = -1;
		String sql = "INSERT INTO T_MB_COMMENT(C_ID, C_U_ID, C_M_ID, C_PID, M_CONTENT, C_DATE)" +
				" VALUES(NULL, ?, ?, ?, ?, now())";
		DBConnect db = new DBConnect();
		db.setAutoCommit(false);
		
		db.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);		
		db.setInt(1, cmt.getC_U_ID());
		db.setInt(2, cmt.getC_M_ID());
		db.setInt(3, cmt.getC_PID());
		db.setString(4, cmt.getC_CONTENT());
		try {
			db.excute();
			flag = db.getGeneratedKeys();
			db.commit();
			
		} catch (MySQLIntegrityConstraintViolationException e) {
			// 数据重复
			flag = -1;
		} finally{
			db.setAutoCommit(true);
			db.close();
		}
		return flag;
	}
	public boolean Delete(final int CID){
		final DBConnect db = new DBConnect();
		final String sql = "DELETE FROM T_MB_COMMENT WHERE C_ID = ?";
		boolean isSucceed = false;
		db.setAutoCommit(false);
		db.prepareStatement(sql);
		try {
			db.setInt(1, CID);
			isSucceed = db.excute();
			db.commit();
		} catch (final Exception ex) {
			ex.printStackTrace();
		} finally {
			db.setAutoCommit(true);
			db.close();
		}
		return isSucceed;
	}
	/**
	 * @berif 	按微博编号得到 相关评论
	 * @param 	cid 微博编号
	 * @return 	评论列表
	 */
	public List<T_MB_COMMENT> GetCmtList(final int cid) {
		final List<T_MB_COMMENT> cmtList = new ArrayList<T_MB_COMMENT>();
		final DBConnect db = new DBConnect();
		final String sql = "select * from T_MB_COMMENT where C_M_ID = ? order by C_DATE desc";
		db.prepareStatement(sql);
		db.setInt(1, cid);
		db.excuteQuery();
		try {
			while (db.next()) {
				final T_MB_COMMENT t = new T_MB_COMMENT();
				t.setC_ID(db.getInt("C_ID"));
				t.setC_U_ID(db.getInt("C_U_ID"));
				t.setC_M_ID(db.getInt("C_M_ID"));
				t.setC_PID(db.getInt("C_PID"));
				t.setC_CONTENT(db.getString("C_CONTENT"));
				t.setC_DATE(db.getTimestamp("C_DATE"));
				cmtList.add(t);
			}
		} catch (final Exception ex) {
			ex.printStackTrace();
			return null;
		} finally {
			db.close();
		}
		return cmtList;
	}
}
